<script setup lang="ts">
import SockJS from 'sockjs-client/dist/sockjs.min.js'
import { Stomp } from "@stomp/stompjs";

// bun add sockjs-client @stomp/stompjs

// 消息列表
const messages = ref();
// 消息类型
export type message = {
  messageId: string;
  senderId: string;
  receiverId: string;
  groupId: string;
  content: string;
  sendTime: string;
  type: string;
};
// 输入的数据
const textarea = ref();

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
let stompClient: any = null;

// 连接到服务端，后续改为登录后自动连接 WebSocket
const connect = () => {
  // 创建 Sockjs 客户端
  const socket = new SockJS("http://localhost:8080/ws");
  // 创建 Stomp 客户端
  stompClient = Stomp.over(socket);

  // 连接到 WebSocket 服务器并订阅消息主题
  stompClient.connect({}, (frame: string) => {
    console.log('连接: ', frame);
    // 订阅群聊 topic
    // 订阅 /topic/messages 路径，接收服务器发送的消息
    // 订阅地址要和 @SendTo 或者 @SendToUser 注解的路径一致
    stompClient.subscribe("/topic/messages", (message: message) => {
      console.log(message);
    });

    // 订阅私聊 queue
    // 订阅私聊消息队列
    stompClient.subscribe("/user/queue/messages", (message: message) => {
      console.log(message);
    });
  }, (error: string) => {
    console.error('连接失败:', error);
    alert('无法连接到 WebSocket 服务器.');
  });
}

// 断开连接
const disconnect = () => {
  if (stompClient) {
    stompClient.disconnect();
  }
  console.log("Disconnected");
}

// 发送消息
const sendMessage = () => {
  if (stompClient && stompClient.connected) {
    console.log("Sending message...");
    // 发送消息，需要带上 /app 前缀，然后接 @MessageMapping 注解的路径
    stompClient.send("/app/messages", {}, JSON.stringify({
      "messageId": "1",
      "senderId": "1",
      "receiverId": "2",
      "groupId": "1",
      "content": "Hello, World!",
      "sendTime": "2023-07-01T12:00:00",
    }))
    console.log("Message sent.");
  } else {
    console.log("Stomp client not connected.");
    alert('未连接到 WebSocket 服务器.');
  }
}


onMounted(() => {
  connect();
})

onBeforeUnmount(() => {
  stompClient.disconnect();
})
</script>

<template>
  <h1>WebSocket STOMP Chat</h1>

  <el-button-group>
    <el-button type="primary" @click="connect">上线</el-button>
    <el-button type="danger" @click="disconnect">下线</el-button>
  </el-button-group>

  <textarea id="messages" rows="10" cols="50" readonly></textarea>

  <!-- 消息展示 -->
  <el-input
      style="width: 800px; height: 600px"
      type="textarea"
      readonly
  >
    <!--    消息条目-->
    <div v-for="message in messages" :key="message.messageId">
      {{ message.content }}
    </div>
  </el-input>

  <!-- 消息输入 -->
  <el-input
      v-model="textarea"
      maxlength="30"
      style="width: 400px"
      placeholder="键入消息..."
      show-word-limit
      type="textarea"
  />
  <el-button type="primary" @click="sendMessage">发送</el-button>
</template>

<style scoped lang="scss">

</style>